module.exports = function(sequelize, DataTypes) {
  var helper = require('../lib/merge')
  var prototype = require('./mixins/TaskMixin')
  var rating = require('./mixins/RatingMixin')

  var Task = sequelize.define(
    'Task',
    helper.mergeWithArray(
      {
        name: {
          type: DataTypes.STRING
        },
        type: {
          type: DataTypes.STRING(30),
          defaultValue: 'liberty'
        },
        textbookId: {
          type: DataTypes.INTEGER,
          defaultValue: 0
        },
        courseId: {
          type: DataTypes.INTEGER,
          defaultValue: 0
        },
        finishCount: {
          type: DataTypes.INTEGER,
          defaultValue: 0
        },
        userCount: {
          type: DataTypes.INTEGER,
          defaultValue: 0
        },
        unreadCount: {
          type: DataTypes.INTEGER,
          defaultValue: 0,
          comment: 'Total unread message number on this task'
        },
        prePublishAt: {
          type: DataTypes.DATE
        },
        isPublished: {
          type: DataTypes.INTEGER(1)
        }
      },
      prototype(DataTypes).attributes,
      rating(DataTypes).attributes
    ),
    helper.mergeWithArray(
      {
        tableName: 'tasks',
        indexes: [
          {
            name: 'documentId_idx',
            fields: ['documentId']
          },
          {
            name: 'versionId_idx',
            fields: ['versionId']
          },
          {
            name: 'ownerId_idx',
            fields: ['ownerId']
          },
          {
            name: 'userId_idx',
            fields: ['userId']
          },
          {
            name: 'groupId_idx',
            fields: ['groupId']
          }
        ],
        comments: 'Task instances from Document'
      },
      prototype(DataTypes).options,
      rating(DataTypes).options
    )
  )

  Task.associate = function(models) {
    this.belongsTo(models.Document, {
      as: 'Prototype',
      foreignKey: 'documentId',
      constraints: false
    })
    this.belongsTo(models.Document, {
      as: 'Version',
      foreignKey: 'versionId',
      constraints: false
    })
    this.belongsTo(models.User, {
      as: 'Owner',
      foreignKey: 'ownerId',
      constraints: false
    })
    this.belongsTo(models.User, {
      as: 'ToUser',
      foreignKey: 'userId',
      constraints: false
    })
    this.belongsTo(models.Group, {
      as: 'ToGroup',
      foreignKey: 'groupId',
      constraints: false
    })
  }
  return Task
}
